package algorithm.sort;

import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;

/**
 * 冒泡排序
 */
public class BubbleSort {

    private final int[] arr = new int[10];

    @Before
    public void init() {
        for (int i = 0, j = arr.length; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * j);
        }
    }

    @Test
    public void sort() {
        System.out.println("排序前:" + Arrays.toString(arr));
        for (int i = 0, len = arr.length; i < len; i++) {
            boolean complete = true;
            for (int j = 0; j < len - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    arr[j] = arr[j] ^ arr[j + 1];
                    arr[j + 1] = arr[j] ^ arr[j + 1];
                    arr[j] = arr[j] ^ arr[j + 1];
                    complete = false;
                }
            }
            if(complete){
                break;
            }
        }
        System.out.println("排序后:" + Arrays.toString(arr));
    }
}
